<?php
namespace Admin\Controller;
use Think\Controller;
class MemberController extends BaseController
{
    protected $memberModel;
    public function __construct()
    {
        parent::__construct();
        $this->memberModel = D('member');
    }
    public function add()
    {
    	if(IS_POST)
    	{
    		$model = D('Member');
    		if($model->create(I('post.'), 1))
    		{
    			if($id = $model->add())
    			{
    				$this->success('添加成功！', U('lst?p='.I('get.p')));
    				exit;
    			}
    		}
    		$this->error($model->getError());
    	}

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '添加瑜伽馆会员表',
			'_page_btn_name' => '瑜伽馆会员表列表',
			'_page_btn_link' => U('lst'),
		));
		$this->display();
    }
    public function userToMember()
    {
        $userData = D('User')->find(I('get.id'));
    	if(IS_POST)
    	{
    		$model = D('Member');
    		if($model->create(I('post.'), 1))
    		{
    			if($id = $model->add())
    			{
    				$this->success('添加成功！', U('lst?p='.I('get.p')));
    				exit;
    			}
    		}
    		$this->error($model->getError());
    	}

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '升级成会员',
			'userData' => $userData,
		));
		$this->display('userToMember');
    }
    public function edit()
    {
    	$id = I('get.id');
    	if(IS_POST)
    	{
    		$model = D('Member');
    		if($model->create(I('post.'), 2))
    		{
    			if($model->save() !== FALSE)
    			{
    				$this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
    				exit;
    			}
    		}
    		$this->error($model->getError());
    	}
    	$model = M('Member');
    	$data = $model->find($id);
    	$this->assign('data', $data);

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '修改瑜伽馆会员表',
			'_page_btn_name' => '瑜伽馆会员表列表',
			'_page_btn_link' => U('lst'),
		));
		$this->display();
    }
    public function delete()
    {
    	$model = D('Member');
    	if($model->delete(I('get.id', 0)) !== FALSE)
    	{
    		$this->success('删除成功！', U('lst', array('p' => I('get.p', 1))));
    		exit;
    	}
    	else 
    	{
    		$this->error($model->getError());
    	}
    }
    public function lst()
    {
    	$model = D('Member');
    	$data = $model->search();
    	$this->assign(array(
    		'data' => $data['data'],
    		'page' => $data['page'],
    	));

		// 设置页面中的信息
		$this->assign(array(
			'_page_title' => '瑜伽馆会员表列表',
			'_page_btn_name' => '添加瑜伽馆会员表',
			'_page_btn_link' => U('add'),
		));

		$this->card = M('card')->field("id,name,effective_day,effective_frequency")->where(array('company_id'=>session('admin.company_id')))->select();
    	$this->display();
    }

    /**
     * @name 获取会员信息
     * @desc
     * @auther ycp
     * @param $id
     * @return string
     */
    public function getMemberById(){
        $id = I('post.id');
        $data = D('member')->find($id);
        $follow_data = M('follow')->where([
            'member_id'=>['eq',$id],
            'company_id'=>['eq',session('admin.company_id')]
        ]
        )->select();
        if($data){
            $this->ajaxReturn(['status'=>'success','msg'=>'','data'=>$data,'follow_data'=>$follow_data]);
        }else{
            $this->ajaxReturn(['status'=>'error','msg'=>'请求失败']);
        }
    }

    /**
     * @name  修改积分
     * @desc
     * @auther ycp
     */
    public function changePoints()
    {
        if(IS_AJAX){
            $id = I('post.member_id');
            $method = I('post.type');
            $points_num = I('post.points_num');
            //原来的积分
            $data = $this->memberModel->find($id);
            if($method == 'plus'){
                $points = $data['jifen']+$points_num;
                $this->memberModel->where([
                    'id'=>['eq',$id]
                ])->save(
                    ['jifen'=>$points]
                );
                $this->ajaxReturn(['status'=>'success','msg'=>'积分添加成功！']);
            }else{
                $points = $data['jifen']-$points_num;
                $this->memberModel->where([
                    'id'=>['eq',$id]
                ])->save(
                    ['jifen'=>$points]
                );
                $this->ajaxReturn(['status'=>'success','msg'=>'积分减少成功！']);
            }
        }
    }

    /**
     * @name 账户充值
     * @desc
     * @auther ycp
     */
    public function changeAccount()
    {
        if(IS_AJAX){
            $id = I('post.member_id');
            $add_num = I('post.addCardSavingNums');
            //原来的账户金额
            $data = $this->memberModel->find($id);
            $points = $data['member_account']+$add_num;
            $res = $this->memberModel->where([
                'id'=>['eq',$id]
            ])->save(
                ['member_account'=>$points]
            );
            if($res){
                $this->ajaxReturn(['status'=>'success','msg'=>'充值成功！']);
            }else{
                $this->ajaxReturn(['status'=>'error','msg'=>'充值失败！']);
            }
        }
    }

    /**
     *
     */
    public function add_file()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize   =     3145728 ;// 设置附件上传大小
        //$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->rootPath  =     './Public/upload/huiyuan/'; // 设置附件上传根目录
        $upload->savePath  =     ''; // 设置附件上传（子）目录
        // 上传文件
        $info   =   $upload->upload();
        $file = './Public/upload/huiyuan/'.$info['import']['savepath'].$info['import']['savename'];

        $data = import_excel($file);
        $count =  0;
        $ncount = 0;

        foreach ($data as $k=>$v)
        {
            if($k>1)
            {
                $arr['username'] = $v['0'];
                $arr['telphone'] = $v['1'];
                $arr['company_id']= session('admin.company_id');
                $res = M("member")->where($arr)->find();
                if(!$res)
                {
                    $card_id = M("Card")->where(array("name"=>array("like","%".$v['2']."%")))->getField("id");

                    $arr['card_id'] = $card_id?$card_id:'0';
                    $arr['start_time'] = $v['3'];
                    $arr['end_time'] = $v['4'];
                    $arr['class_account'] = $v['5']?$v['5']:'0';
                    $arr['member_account'] = $v['6']?$v['6']:'0';
                    M("member")->data($arr)->add();
                    $count++;
                }else
                {
                    $ncount++;
                }

            }
        }

        $this->success($ncount."条数据重复"."/".$count."条数据导入成功！");
    }

    /**
     * @name 修改会员
     * @desc
     * @auther ycp
     */
    public function editOrAdd()
    {
        if(IS_AJAX){
            $data = I('post.');
            $model = D('Member');
            if($data['id']){
                if($model->create($data, 2))
                {
                    if($model->save() !== FALSE)
                    {
                        $this->ajaxReturn(['status'=>'success','msg'=>'会员修改成功！']);
                    }
                }else{
                    $this->ajaxReturn(['status'=>'error','msg'=>'会员修改失败！']);

                }
            }else{
                if($model->create($data, 1))
                {
                    if($model->save() !== FALSE)
                    {
                        $this->ajaxReturn(['status'=>'success','msg'=>'会员添加成功！']);
                    }
                }else{
                    $this->ajaxReturn(['status'=>'error','msg'=>'会员添加失败！']);

                }
            }

        }
    }

    /**
     * @name 修改会员头像
     * @desc
     * @auther ycp
     */
    public function uploadsLogo()
    {

          $data = I('post.');
          $model = D('Member');
          if($res = $model->create($data, 2))
          {
              if($model->save() !== FALSE)
              {
                  $this->success('修改成功！', U('lst', array('p' => I('get.p', 1))));
                  exit;
              }
          }else{
              $this->error($model->getError());

          }

    }

    /**
     * @name 跟踪记录
     * @desc
     * @auther ycp
     */
    public function followMemberRecord(){
        if(IS_AJAX){
            $data = I('post.');
            $data['followContent'] = trim($data['followContent']);
            $data['company_id'] = session('admin.company_id');
            $model = M('follow');
            if($model->create($data, 1))
            {
                if($res=$model->add($data) !== FALSE)
                {
                    $this->ajaxReturn(['status'=>'success','msg'=>'会员跟踪记录成功！']);
                }else{
                    $this->ajaxReturn(['status'=>'error','msg'=>$model->getError()]);
                }
            }else{
                $this->ajaxReturn(['status'=>'error','msg'=>'会员跟踪记录失败！']);
            }
        }
    }

    public function add_kaika()
    {
        $where['username'] = I('cust_name');
        $where['telphone'] = I('cust_mobile');
        $res = M('member')->where($where)->find();
        if($res)
        {
            $save['start_time'] = I('card_begin_date');
            $save['end_time'] = I('card_end_date');
            $reinfo = M('member')->where($where)->save($save);
            if($reinfo)
            {
                $this->success("操作成功！");
            }else
            {
                $this->error('操作失败');
            }
        }else
        {
            $this->error('获取会员失败，请重新设置！');
        }
    }

    public function get_course()
    {
        $id = I('id');
        $card_id = M("member")->where(array("id"=>$id))->getField("card_id");
        $effective_day = M('card')->where(array("id"=>$card_id))->getField('effective_day');
        die(json_encode($effective_day));
    }

    public function get_card_data()
    {
        $id = I('id');
        $card_id = M("member")->field("start_time,end_time,card_id")->where(array("id"=>$id))->find();
        $arr['effective_day'] = M('card')->where(array("id"=>$card_id['card_id']))->getField('effective_day');
        $arr['start_time'] = $card_id['start_time'];
        $arr['end_time'] = $card_id['end_time'];
        die(json_encode($arr));
    }

    public function card_type()
    {
        $id = I('id');
        $effective_day = M('card')->where(array("id"=>$id))->getField('effective_day');
        die(json_encode($effective_day));
    }

    public function sell_user_card()
    {
        var_dump(I());
        $where['username'] =I('cust_name');
        $where['telphone'] =I('cust_mobile');

        $res = M('member')->where($where)->find();
        if($res)
        {
            $save['card_id'] = I('card_type');
            $save['pay_way'] = I('pay_way');
            $save['sellNote'] = i('comment');
            $save['pay_account'] = I('card_price');
            $save['member_count'] = I('card_times')?I('card_times'):'0';
            $save['member_zk']  =I('card_discount')?I('card_discount'):'1';
            $save['member_account'] = I('card_saving');
            $save['jifen']  =I('card_points');
            $reinfo = M('member')->where($where)->save($save);
            if($reinfo)
            {
                $this->success("操作成功！");
            }else
            {
                $this->error('操作失败');
            }
        }else
        {
            $this->error('获取会员失败，请重新设置！');
        }

    }

}